<?php
/**
 * Created by PhpStorm.
 * User: childeYin<尹少爷>
 * Date: 18/07/2018
 * Time: 8:32 AM
 */
// use Zaly\Proto\Site\ApiSiteGroupRequest;

class Api_Site_NlgoinController extends \BaseController
{
    private $classNameForRequest = '\Zaly\Proto\Site\ApiSiteLoginRequest';
    // private $classNameForRequest = '';
    // private $classNameForRequest = '\Zaly\Proto\Site\ApiSiteGroupRequest';
    private $classNameForResponse = '\Zaly\Proto\Site\ApiSiteLoginResponse';
    private $sessionVerifyAction = "api.session.verify";
    private $permissionJoin = \Zaly\Proto\Core\GroupJoinPermissionType::GroupJoinPermissionMember;
    private $canGuestReadMsg = false;
    private $pinyin;
    // public $siteCookieName = "zaly_site_user";
    private $maxMembers = -1;
    private $groupNameLength = 20;
    private $startGroupCreateTime;
    private $createGroupTimeOut = 60; //1分钟超时
    private $groupIdLength = 10;
    public $siteCookieName = "zaly_site_user";
    private $cookieTimeOut = 2592000;//30天 单位s

    public function rpcRequestClassName()
    {
        return $this->classNameForRequest;
    }
      /**
     * @param \Zaly\Proto\Site\ApiSiteGroupRequest $request
     * 
     */
    public function rpc(\Google\Protobuf\Internal\Message $request, \Google\Protobuf\Internal\Message $transportData){
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
 
        //写的请求不行 加不进去
        // $json_data = file_get_contents('php://input');
        // 解析 JSON 数据
        // $data = json_decode($json_data, true);
        $this->pinyin = new \Overtrue\Pinyin\Pinyin();
        $this->startGroupCreateTime = time();
        // var_dump($_GET);
        
        // die;
        $data=[
            'buyer_id'=>$_GET['buyer_id'],
            'seller_id'=>$_GET['seller_id'],
            'order_id'=>$_GET['order_id'],
        ];
     
        
        if($data['buyer_id']&&$data['seller_id']&&$data['order_id']){

            //  先查询用户id

           //是否注册过---
           $res=$this->ctx->PassportPasswordTable->getUserByUserId($data['buyer_id']);  //买家
           $res1=$this->ctx->PassportPasswordTable->getUserByUserId($data['seller_id']); //卖家
               if(empty($res)){
                   $loginName=$data['buyer_id'];
                   $email=$data['buyer_id'];
                   $password='123456';
                   $nickname=$data['buyer_id'];
                   $invitationCode='';
                   $sitePubkPem='';
                   $avatar='';
                   //没有注册 注册一下
                   $preSessionId=$this->registerUserForPassport($data['buyer_id'],$loginName, $email, $password, $nickname, $invitationCode, $sitePubkPem, $avatar);
               }else{
                   $sitePubkPem =  $this->ctx->Site_Config->getConfigValue(SiteConfig::SITE_ID_PUBK_PEM);
                   // $user = $this->verifyUserInfo($data['buyer_id'], 123456);
                   $preSessionId = $this->generatePreSessionId($res, $sitePubkPem);
               }
               if(empty($res1)){
                   //没有注册 注册一下
                   $preSessionId2=$this->registerUserForPassport($data['seller_id'],$data['seller_id'], '', 123456, $data['seller_id'], '', '', '');
               }else{
                $sitePubkPem =  $this->ctx->Site_Config->getConfigValue(SiteConfig::SITE_ID_PUBK_PEM);
                // $user = $this->verifyUserInfo($data['buyer_id'], 123456);
                $preSessionId2 = $this->generatePreSessionId($res1, $sitePubkPem);
               }
               //买家登录
                   $resdata=[
                           'preSessionId'=>$preSessionId,
                           'preSessionId2'=>$preSessionId2
                   ];
                 
                   $userProfile = $this->ctx->Site_Login->doLogin('', $preSessionId, '', '', []);
                   //买家和卖家一起登录注册账号
                   $userProfile2 = $this->ctx->Site_Login->doLogin('', $preSessionId2, '', '', []);

                   $realSessionId = $userProfile['sessionId'];
                   $realSessionId2 = $userProfile2['sessionId'];


                   $user = $this->ctx->SiteUserTable->getUserByLoginName($data['buyer_id']);
                   $user2 = $this->ctx->SiteUserTable->getUserByLoginName($data['seller_id']);
                
                //   $existsUser= $this->ctx->SiteGroupUserTable->getUserIDExist([$user['userId'],$user2['userId']]);
                //查找订单号 没有就创建群料
                        $existsUser= $this->ctx->SiteGroupTable->getGroupProfileByName($_GET['order_id']);
                    //       var_dump($_GET['order_id']);
                    // var_dump($existsUser['0']['groupId']);
                    // die;
                    
            // var_dump($existsUser);
            //     die;
                   $groupId='';
                   if(!empty($existsUser)){
                           //不存在 并且返回的是groupid数组
                       $groupId=$existsUser['0']['groupId'];
                    //    echo json_encode(['groupId'=>$groupId]);
                    //    // var_dump('群id'.$groupId);
                    //    die;
                   }else{
                     
                       $groupProfile=$this->insertGroup($data['order_id'],'');
                       if (!$groupProfile) {
                        throw new Exception("create group failed");
                      }
                      
                        $groupId = $groupProfile['groupId'];
                        //邀请成员
                             /// 公开的直接进入
                       $userList = [
                           '0'=>$user['userId'],
                           '1'=>$user2['userId'],
                       ];
                       $this->addMemberToGroup($userList, $groupId);
                                       // 创建成功了之后，代发消息，
   
                   $noticeText = ZalyText::$keyGroupCreate;
                   
                    //   所属银行:XXXXXXXXX
                    // 持卡人姓名:XXXXXXXXX
                    // 卡号:XXXXXXXXX
                       
                      
                       
$this->ctx->Message_Client->proxyGroupNoticeMessage($userId='c7c78834183243d1a48e0cd08ae829794d30385d', $groupId, 'Ngân hàng sở hữu :'. $_GET['bank']);
$this->ctx->Message_Client->proxyGroupNoticeMessage($userId='c7c78834183243d1a48e0cd08ae829794d30385d', $groupId, 'Tên chủ thẻ :'.$_GET['bankname']);
$this->ctx->Message_Client->proxyGroupNoticeMessage($userId='c7c78834183243d1a48e0cd08ae829794d30385d', $groupId, 'Số thẻ :'.$_GET['banknumber']);
               
                //    setcookie($this->siteCookieName, $realSessionId, time() + $this->cookieTimeOut, "/", "", false, true);
                   
                 
                //    $userExists = $this->checkUserExists($loginName);

            
                
                    // echo json_encode($resdata);
                    // die;
                }
            // 获取请求的协议
                // $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
                
                // // 获取请求的主机名
                // $host = $_SERVER['HTTP_HOST'];
                
                // // 获取请求的 URI
                // $uri = $_SERVER['REQUEST_URI'];
                
                // // 构建完整的 URL
                // $request_url = $protocol . "://" . $host;
                $request_url =  $_GET['p_url']?$_GET['p_url']:'';
                // 输出完整的请求地址
                // echo $request_url;
                if($_GET['user_id']==$data['buyer_id']){
                        //买家
                        header("Location:http://kf1.bitfinexa.com/index.php?action=page.index&cookie=".$realSessionId.'&groupId='.$groupId.'&p_url='.$request_url);
                        exit();
                }else{
                    header("Location:http://kf1.bitfinexa.com/index.php?action=page.index&cookie=".$realSessionId2.'&groupId='.$groupId.'&p_url='.$request_url);
                    exit();
                }
               
            }
    }
       //注册
       private function registerUserForPassport($userId,$loginName, $email, $password='123456', $nickname, $invitationCode, $sitePubkPem, $avatar = null)
       {
           try {
               $tag = __CLASS__ . '-' . __FUNCTION__;
   
               $this->ctx->BaseTable->db->beginTransaction();
               // $userId = ZalyHelper::generateStrId();
               $userInfo = [
                   "userId" => $userId,
                   "loginName" => $loginName,
                   "email" => $email,
                   "password" => password_hash($password, PASSWORD_BCRYPT),
                   "nickname" => $nickname,
                   "invitationCode" => $invitationCode,
                   "timeReg" => ZalyHelper::getMsectime(),
                   "avatar" => $avatar
               ];
               $this->ctx->PassportPasswordTable->insertUserInfo($userInfo);
               $preSessionId = ZalyHelper::generateStrId();
   
               $preSessionInfo = [
                   "userId" => $userId,
                   "preSessionId" => $preSessionId,
                   "sitePubkPem" => base64_encode($sitePubkPem)
               ];
               $this->ctx->PassportPasswordPreSessionTable->insertPreSessionData($preSessionInfo);
   
               $this->ctx->BaseTable->db->commit();
               return $preSessionId;
           } catch (Exception $ex) {
               $this->ctx->Wpf_Logger->error($tag, "error_msg=" . $ex);
               $this->ctx->BaseTable->db->rollback();
               throw new Exception($ex);
           }
       }
       private function generatePreSessionId($user, $sitePubkPem)
       {
           $preSessionId = ZalyHelper::generateStrId();
   
           try {
               $preSessionInfo = [
                   "userId" => $user['userId'],
                   "preSessionId" => $preSessionId,
                   "sitePubkPem" => base64_encode($sitePubkPem)
               ];
   
               $this->ctx->PassportPasswordPreSessionTable->insertPreSessionData($preSessionInfo);
           } catch (Exception $ex) {
               $preSessionInfo = [
                   "preSessionId" => $preSessionId,
                   "sitePubkPem" => base64_encode($sitePubkPem)
               ];
               $where = [
                   "userId" => $user['userId']
               ];
               $this->ctx->PassportPasswordPreSessionTable->updatePreSessionData($where, $preSessionInfo);
           }
           return $preSessionId;
       }

       private function insertGroup($groupName, $groupAvatar,$userId='c7c78834183243d1a48e0cd08ae829794d30385d')
       {
           $tag = __CLASS__ . '-' . __FUNCTION__;
           try {
   
               if (time() - $this->startGroupCreateTime > $this->createGroupTimeOut) {
                   $this->ctx->BaseTable->db->rollBack();
                   $errorCode = $this->zalyError->errorGroupCreate;
                   $errorInfo = $this->zalyError->getErrorInfo($errorCode);
                   $this->setRpcError($errorCode, $errorInfo);
                   return false;
               }
               $groupId = $this->ctx->ZalyHelper->generateStrKey($this->groupIdLength);
               $groupId = strtolower($groupId);
               $nameInLatin = $this->pinyin->permalink($groupName, "");
               $groupProfile = [
                   "groupId" => $groupId,
                   "name" => $groupName,
                   "nameInLatin" => $nameInLatin,
                   "avatar" => $groupAvatar,
                   "owner" => $userId,
                   "description" => "",
                   "speakers" => "",
                   "maxMembers" => $this->maxMembers,
                   "permissionJoin" => $this->permissionJoin,
                   "canGuestReadMessage" => $this->canGuestReadMsg ? 1 : 0,
                   "status" => 1,
                   "timeCreate" => $this->ctx->ZalyHelper->getMsectime()
               ];
               $groupOwnerInfo = [
                   'groupId' => $groupId,
                   'userId' => $userId,
                   'memberType' => \Zaly\Proto\Core\GroupMemberType::GroupMemberOwner,
                   'timeJoin' => $this->ctx->ZalyHelper->getMsectime()
               ];
               $this->ctx->BaseTable->db->beginTransaction();
               $this->ctx->BaseTable->insertData($this->ctx->SiteGroupTable->table, $groupProfile, $this->ctx->SiteGroupTable->columns);
               $this->ctx->BaseTable->insertData($this->ctx->SiteGroupUserTable->table, $groupOwnerInfo, $this->ctx->SiteGroupUserTable->columns);
               $this->ctx->BaseTable->db->commit();
               return $groupProfile;
           } catch (Exception $ex) {
               $this->ctx->Wpf_Logger->error($tag, "error_msg=" . $ex->getMessage());
               $this->ctx->BaseTable->db->rollBack();
   //            $this->insertGroup($groupName, $this->groupIdLength++);
           }
       }
       //邀请加入群聊
       private function addMemberToGroup($userIds, $groupId)
       {
           $tag = __CLASS__ . "_" . __FUNCTION__;
           try {
               if (!$userIds) {
                   $errorCode = $this->zalyError->errorUserIdExists;
                   $errorInfo = $this->zalyError->getErrorInfo($errorCode);
                   $this->setRpcError($errorCode, $errorInfo);
                   throw new Exception($errorInfo);
               }
               $existsUserId = $this->ctx->SiteGroupUserTable->getUserIdExistInGroup($userIds, $groupId);
               $notExistsUserId = $userIds;
               if ($existsUserId) {
                   $notExistsUserId = array_diff($userIds, $existsUserId);
               }
               if (!count($notExistsUserId)) {
                   return true;
               }
   
               //$groupPointer
               $groupPointer = $this->ctx->SiteGroupMessageTable->queryMaxIdByGroup($groupId);
   
               $this->ctx->BaseTable->db->beginTransaction();
               foreach ($notExistsUserId as $userId) {
   
                   //insert group Message pointer
   //            $groupMessagePointerInfo = [];
                   $this->ctx->SiteGroupMessageTable->updatePointer($groupId, $userId, "", $groupPointer);
   
                   //insert into siteGroupUser
                   $groupUserInfo = [
                       'groupId' => $groupId,
                       'userId' => $userId,
                       'memberType' => \Zaly\Proto\Core\GroupMemberType::GroupMemberNormal,
                       'timeJoin' => $this->ctx->ZalyHelper->getMsectime()
                   ];
                   $this->ctx->BaseTable->insertData($this->ctx->SiteGroupUserTable->table, $groupUserInfo, $this->ctx->SiteGroupUserTable->columns);
               }
               $this->ctx->BaseTable->db->commit();
           } catch (Exception $ex) {
               $this->ctx->BaseTable->db->rollback();
               $this->ctx->Wpf_Logger->error($tag, $ex->getMessage());
               $errorCode = $this->zalyError->errorGroupInvite;
               $errorInfo = $this->zalyError->getErrorInfo($errorCode);
               $this->setRpcError($errorCode, $errorInfo);
               throw new Exception("invite failed");
           }
       }
}